import { parseRSSFeed } from './universal-rss-parser.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前脚本文件所在目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取配置文件
const configPath = path.join(__dirname, 'rss-feeds-config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));

// 筛选 AI 相关的 RSS 源（可以根据需要调整筛选条件）
const aiFeeds = config.feeds.filter(feed => 
  feed.name.toLowerCase().includes('ai') || 
  feed.name.toLowerCase().includes('business') ||
  feed.outputFile.toLowerCase().includes('ai')
);

/**
 * 更新 AI 资讯列表页面
 */
async function updateAINewsList() {
  const rootDir = path.resolve(process.cwd());
  const outputPath = path.join(rootDir, 'lawyerch.cn', 'ai-news.md');
  const dataDir = path.join(rootDir, 'data');

  // 收集所有 AI 相关的文章
  let allItems = [];

  for (const feed of aiFeeds) {
    const dataFile = path.join(dataDir, feed.outputFile);
    if (fs.existsSync(dataFile)) {
      const data = JSON.parse(fs.readFileSync(dataFile, 'utf-8'));
      // 为每个文章添加来源信息
      const items = data.items.map(item => ({
        ...item,
        source: feed.name
      }));
      allItems = allItems.concat(items);
    }
  }

  // 按日期排序（最新的在前）
  const sortedItems = [...allItems].sort((a, b) => {
    const dateA = new Date(a.pubDate || 0);
    const dateB = new Date(b.pubDate || 0);
    return dateB - dateA;
  });

  // 限制显示数量（最多显示 30 条）
  const displayItems = sortedItems.slice(0, 30);

  let content = `---
title: AI资讯-人工智能最新动态|AI技术前沿|AI行业新闻
description: 最新AI资讯，包含人工智能技术前沿、AI行业动态、AI应用实践等权威信息。
head:
  - - meta
    - name: keywords
      content: AI资讯,人工智能,AI技术,AI行业,机器学习,深度学习,大模型
---

# AI资讯

最新人工智能资讯，关注AI技术前沿，了解AI行业动态。

---

## 🤖 最新资讯

<div class="article-collection">
  <div class="collection-info">
    <span class="collection-count">${displayItems.length}条资讯</span>
    <span class="collection-desc">每日更新最新AI技术与行业动态</span>
  </div>
</div>

---

<style>
.news-image-container {
  width: 100%;
  margin: 20px 0;
  text-align: center;
  overflow: hidden;
  border-radius: 8px;
  background: var(--vp-c-bg);
}

.news-image {
  width: 100%;
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
  object-fit: cover;
}

.news-brief {
  color: var(--vp-c-text-2);
  line-height: 1.8;
  margin: 16px 0;
  font-size: 15px;
}

.news-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 16px 0;
  font-size: 14px;
  color: var(--vp-c-text-2);
}

.news-date {
  display: flex;
  align-items: center;
  gap: 4px;
}

.news-source {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  background: var(--vp-c-brand-soft);
  color: var(--vp-c-brand-1);
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.news-author {
  display: flex;
  align-items: center;
  gap: 4px;
}

.news-link-btn {
  display: block;
  width: 100%;
  margin-top: 20px;
  padding: 14px 24px;
  background: var(--vp-c-brand-1);
  color: white !important;
  text-decoration: none !important;
  text-align: center;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.news-link-btn:hover {
  background: var(--vp-c-brand-3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.news-title-link {
  color: var(--vp-c-text-1);
  text-decoration: none;
  transition: color 0.3s ease;
}

.news-title-link:hover {
  color: var(--vp-c-brand-1);
}

.dark .news-source {
  background: rgba(59, 130, 246, 0.2);
  color: var(--vp-c-brand-2);
}

@media (max-width: 768px) {
  .news-link-btn {
    padding: 12px 20px;
    font-size: 15px;
  }
}
</style>

`

  displayItems.forEach((item, index) => {
    const pubDate = item.pubDate ? new Date(item.pubDate).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }) : '';
    
    content += `### ${index + 1}. <a href="${item.link || '#'}" target="_blank" rel="noopener noreferrer" class="news-title-link">${item.title || '无标题'}</a>

${item.imageUrl ? `<div class="news-image-container">
  <img src="${item.imageUrl}" alt="${item.title || 'AI资讯'}" class="news-image" loading="lazy" />
</div>` : ''}

${item.description ? `<div class="news-brief">${item.description}</div>` : ''}

<div class="news-meta">
  ${pubDate ? `<div class="news-date">
    <span>📅</span>
    <span>${pubDate}</span>
  </div>` : ''}
  ${item.author ? `<div class="news-author">
    <span>✍️</span>
    <span>${item.author}</span>
  </div>` : ''}
  ${item.source ? `<div class="news-source">来源: ${item.source}</div>` : ''}
</div>

${item.link ? `<a href="${item.link}" target="_blank" rel="noopener noreferrer" class="news-link-btn">查看原文 →</a>` : ''}

---
`
  })

  content += `## 📬 订阅更新

关注我的微信公众号"陈恒律师日志"，第一时间接收AI资讯推送。

::: tip 订阅方式
扫描网站首页二维码关注公众号，每日获取最新AI技术与行业动态。
:::
`

  fs.writeFileSync(outputPath, content, 'utf-8');
  console.log(`✅ 已更新AI资讯列表: ${outputPath}`);
  console.log(`   共 ${displayItems.length} 条资讯`);
}

// 如果直接运行此文件，执行更新
const isMainModule = import.meta.url === `file://${process.argv[1]?.replace(/\\/g, '/')}` || 
                     process.argv[1]?.endsWith('update-ai-news.js');

if (isMainModule) {
  updateAINewsList().catch(console.error);
}

// 导出函数供其他脚本使用
export { updateAINewsList };

